/* 
 * Copyright (c)	Insighten Intelligent Equipment co.,LTD
 * 
 *  Use of this software is controlled by the terms and conditions found
 *  in the license agreement under which this software has been supplied.
 * 
 */
/** 
 * @file tcp_svr_main.c
 * @brief test tcp server
 * @author taco [tacoee@gmail.com]
 * @version 0.1
 * @date 2010-09-03
 */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/time.h>

#include "tcp_server.h"
#include "rwbuf.h"

void helper(char *program)
{
	fprintf(stderr, "Usage: %s port[1234]\n", program);
}

int main(int argc, char *argv[])
{
	fd_set rset;
	fd_set wset;
	TcpServer *tcp_svr;
	SocketAttr attr = {0, 8092};
	RwBuf *buf;
	Request *req = NULL;
	Request *req_head= NULL;
	Request *req_pos = NULL;
	int maxfd = -1;
	int ret = -1;
	int i;
	int clifd = -1;
	int port;

	if (argc < 2) {
		helper(argv[0]);
		exit(1);
	}

	port = atol(argv[1]);

	FD_ZERO(&rset);
	FD_ZERO(&wset);
	
	tcp_svr = tcp_server_new();
	tcp_server_init(tcp_svr, port, 10, &attr);
	tcp_server_create(tcp_svr);

	maxfd = tcp_svr->fd;


	while(1) {
		FD_SET(tcp_svr->fd, &rset);
		ret = select(maxfd+1, &rset, &wset, NULL, NULL);
		if (FD_ISSET(tcp_svr->fd, &rset)) {
			req = tcp_server_request(tcp_svr, &attr);
			req->buf = buf_new(NULL, NULL);
			buf_init(req->buf, 8092);
			if (req->fd > maxfd) {
				maxfd = req->fd;
			}
			request_enqueue(&req_head, req);
			FD_SET(req->fd, &rset);
			printf("new request! %d\n", __LINE__);
		}
		for(req_pos=req_head; req_pos != NULL; req_pos=req_pos->next) {
			if (FD_ISSET(req_pos->fd, &rset)) {
				/*deal with read*/	
				ret = tcp_server_read(req_pos, 50);
				if (ret > 0) {
					req_pos->buf->wpos += ret;
					fprintf(stderr, "debg line=%d value=%s ret=%d\n", __LINE__, 
							req_pos->buf->mem, ret);
					FD_CLR(req_pos->fd, &rset);
					FD_SET(req_pos->fd, &wset);
				}

			}
			if (FD_ISSET(req_pos->fd, &wset)) {
				/*deal with write*/
				ret = tcp_server_write(req_pos,req_pos->buf->wpos);

				fprintf(stderr, "debg line=%d value=%s ret=%d\n", __LINE__, 
							req_pos->buf->mem, ret);
				if (ret == req_pos->buf->wpos) {
					req_pos->status = DONE;
				}

				if (req_pos->status == DONE) {
					buf_destroy(req_pos->buf);
					tcp_server_dis_client(req_pos, tcp_svr);
					request_dequeue(&req_head, req_pos);
					printf("Finished one request!\n\n");
					FD_CLR(req_pos->fd, &wset);
				}
			}
		} /*for*/
	} /*while*/

	tcp_server_destroy(tcp_svr);

	return 0;
}


